import React, { createContext, useState, useEffect, useCallback } from 'react';
import { Appearance, ColorSchemeName } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { lightColors, darkColors, ThemeColors } from '@/constants/colors';

type ThemeMode = 'light' | 'dark' | 'system';
const THEME_STORAGE_KEY = '@app_theme_mode';

interface ThemeContextType {
  mode: ThemeMode;
  colors: ThemeColors;
  isDark: boolean;
  setMode: (mode: ThemeMode) => void;
}

export const ThemeContext = createContext<ThemeContextType>({
  mode: 'system',
  colors: darkColors,
  isDark: true,
  setMode: () => {},
});

export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [mode, setMode] = useState<ThemeMode>('system');
  const [systemTheme, setSystemTheme] = useState<ColorSchemeName>(Appearance.getColorScheme());
  const [isLoading, setIsLoading] = useState(true);

  // 从存储中加载主题设置
  useEffect(() => {
    const loadThemeMode = async () => {
      try {
        const savedMode = await AsyncStorage.getItem(THEME_STORAGE_KEY);
        if (savedMode && (savedMode === 'light' || savedMode === 'dark' || savedMode === 'system')) {
          setMode(savedMode as ThemeMode);
        }
      } catch (error) {
        console.error('加载主题设置失败:', error);
      } finally {
        setIsLoading(false);
      }
    };

    loadThemeMode();
  }, []);

  // 监听系统主题变化
  useEffect(() => {
    const subscription = Appearance.addChangeListener(({ colorScheme }) => {
      setSystemTheme(colorScheme);
    });

    return () => subscription.remove();
  }, []);

  // 根据模式和系统主题确定当前是否为深色模式
  const isDark = mode === 'system' 
    ? systemTheme === 'dark' 
    : mode === 'dark';

  // 根据是否为深色模式选择颜色
  const colors = isDark ? darkColors : lightColors;

  // 更新主题模式并保存到存储
  const handleSetMode = useCallback(async (newMode: ThemeMode) => {
    setMode(newMode);
    try {
      await AsyncStorage.setItem(THEME_STORAGE_KEY, newMode);
    } catch (error) {
      console.error('保存主题设置失败:', error);
    }
  }, []);

  const contextValue = {
    mode,
    colors,
    isDark,
    setMode: handleSetMode,
  };

  if (isLoading) {
    // 可以返回一个加载指示器或者使用默认主题
    return (
      <ThemeContext.Provider value={contextValue}>
        {children}
      </ThemeContext.Provider>
    );
  }

  return (
    <ThemeContext.Provider value={contextValue}>
      {children}
    </ThemeContext.Provider>
  );
};